import axios from 'axios'
import Finger from '@/utils/fingerprintjs2'
// import md5 from 'js-md5'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
// import Cookies from 'js-cookie'
import { getToken } from '@/utils/auth'
import i18n from '@/locales'
import encrypt from './encrypt'
import dataHandle from './encrypt/encrypt'
Finger.loadUuid()

// create an axios instance
const service = axios.create({
	baseURL: process.env.VUE_APP_BASE_API,
	timeout: 15000
})

const needEncrypt = process.env.VUE_APP_ENCRYPTED === '1'
service.interceptors.request.use(
	async (config) => {
		if (config.params) {
			const keys = Object.keys(config.params)
			keys.forEach((element) => {
				if (
					config.params[element] === ''
					// config.params[element] === '-1' ||
					// config.params[element] === -1
				) {
					config.params[element] = undefined
				}
			})
		}
		if (config.responseType === 'blob') {
			config.timeout = 60 * 1000
		}
		// 上传图片过期时间改为30秒
		if (config?.cb) {
			config.timeout = 30 * 1000
		}
		// 上传资源包文件过期时间改为120秒
		if (config?.uploadFile) {
			config.timeout = 120 * 1000
			delete config.uploadFile
		}
		if (getToken()) {
			config.headers['X-Request-Token'] = getToken()
		} else {
			// const fullPath = router.history.current.fullPath
			await store.dispatch('user/clearAllCaches')
			// router.push(`/login?redirect=${fullPath}`)
			router.push(`/login`)
		}
		if (!store.getters.isZk) {
			config.headers['X-Request-Merchant'] = `${store.getters.merchantInfo.id
				}|${store.getters.merchantInfo.merchantCode}`
			config.headers['merchant-id'] = store.getters.merchantInfo.id
		} else {
			config.headers['X-Request-Merchant'] = '0|BWZK'
			config.headers['merchant-id'] = '0'
		}
		config.headers['X-Request-Sys'] = 1
		config.headers['Content-type'] = 'application/json; charset=utf-8'
		config.headers['ob-secret-version'] = process.env.VUE_APP_SECRET_VERSION
		config.headers['ob-application'] = process.env.VUE_APP_APPLICATION
		config.headers['ob-nonce'] = dataHandle.createNonce()
		config.headers['ob-timestamp'] = dataHandle.createTimestamp()
		config.headers['lang'] = store.getters.language
		// config.headers['X-Request-User'] = `${store.getters.userInfo.id}|darcy`
		config.onUploadProgress = (progressEvent) => {
			const complete =
				((progressEvent.loaded / progressEvent.total) * 100) | 0
			if (config.cb) {
				config.cb(complete)
			}
		}
		config.headers['X-Request-Browser'] = store.getters.finger
		if (
			needEncrypt &&
			!config.data?.append &&
			config.responseType !== 'blob'
		) {
			// if (['dev', 'test'].includes(process.env.VUE_APP_ENV_FLAG)) {
			// 	config.headers['ob-encrypted'] = true
			// }
			config.headers['ob-encrypted'] = true
			config = encrypt.encryptData(config)
		} else {
			config.headers['ob-encrypted'] = false
		}
		return config
	},
	(error) => {
		return Promise.reject(error)
	}
)

service.interceptors.response.use(
	async (response) => {
		if (
			response.config.responseType &&
			response.config.responseType === 'blob' &&
			response.data.type !== 'application/json'
		) {
			return response
		}

		if (
			response.config.responseType === 'blob' &&
			response.data.type === 'application/json'
		) {
			const readFile = () => {
				return new Promise((resolve, reject) => {
					const reader = new FileReader()
					reader.readAsText(response.data)
					reader.onload = () => {
						response.data = reader.result
						if (response.config.method === 'get') {
							response.data = JSON.parse(reader.result)
						} else {
							if (response.config.headers['ob-encrypted']) {
								response.data = reader.result
							} else {
								response.data = JSON.parse(reader.result)
							}
						}
						resolve()
					}
				})
			}
			await readFile()
		}

		const headers = response.config.headers
		// 数据解密, 只对content-type为application/json或者text/plain解密
		const headersContentType = response.headers['content-type'] || ''

		if (
			headers['ob-encrypted'] &&
			response.data &&
			(headersContentType.includes('application/json') ||
				headersContentType.includes('text/plain'))
		) {
			const decryptData = encrypt.decryptData(response.data) || ''
			response.data = JSON.parse(decryptData)
		}

		const res = response.data

		if (res.code !== 200) {
			if (res.code === 800004 || res.code === 2981681) {
				return Promise.reject(res)
			} else if (res.code === 100009) {
				// 拦截导出错误提示
				Message.closeAll()
				Message({
					message: res.message || res.msg || res || 'Error',
					type: 'error'
				})
				return Promise.reject(res)
			} else {
				// if the custom code is not 20000, it is judged as an error.
				if (
					res.code === 10025 ||
					res.code === 20000 ||
					// res.code === 200001 ||
					res.code === 20001 ||
					res.code === 20002 ||
					res.code === 4004 ||
					res.msg === i18n.t('common.utils.fail')
				) {
					// 无效权限
					// const fullPath = router.history.current.fullPath
					await store.dispatch('user/clearAllCaches')
					// router.push(`/login?redirect=${fullPath}`)
					router.push(`/login`)
				}
				Message.closeAll()
				Message({
					message: res.message || res.msg || res || 'Error',
					type: 'error'
				})
				return Promise.reject(
					new Error(res.message || res.msg || 'Error')
				)
			}
		} else {
			return res
		}
	},
	async (error) => {
		let msg = ''
		if (error.response?.status === 401) {
			msg = i18n.t('common.utils.error')
		} else if (error.response?.data?.code === 4091) {
			msg = error.response?.data?.msg
		}
		// 重新赋值超时提示
		if (error.message && error.message.includes('timeout')) {
			msg = i18n.t('common.utils.try_again')
		}
		Message.closeAll()
		Message({
			message: msg || error.message || error.msg,
			type: 'error'
		})
		return Promise.reject(error)
	}
)

export default service
